/**
 * Created by Oswald on 2017/5/5.
 * Edited by WangGY on 2017/5/21 : Add pvCheck method and set pv class
 */
var orderId = GetUrlParam('orderId');

$(function () {
  Highcharts.setOptions({global: {useUTC: false}});

  //块儿 的样式设定
  ibcpPVExecute.ResetStyle();

  //初始化 vp 对象  并对 4状态 统一做修改 和 历史 按钮事件处理
  ibcpPVExecute.Init();

  // if(window.matchMedia){
  //     window.matchMedia('print').addListener(function () {
  //         $('.chartContainer').highcharts().reflow();
  //     })
  // }

});

//根据名称获取Url中某个参数的值
function GetUrlParam(pname) {
  var reg = new RegExp("(^|&)" + pname + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return decodeURI(r[2]);
  }
  return null;
}

/**
 * 执行中的PV处理对象
 * @type {{Init, SaveVal, Exchange}}
 */
var ibcpPVExecute = (function () {

  //初始化
  var InitPV = function () {

    $('[ibcpPV="PV-Chart"]').each(function () {
      //获取PV对象本身
      var pvElement = $(this);
      ibcpChartPV.Init(pvElement);
    });

    $('[ibcpPV="PV-Bottle"]').each(function () {
      //获取PV对象本身
      var pvElement = $(this);
      ibcpPV_Bot.Init(pvElement);
    });

    //称量结果集pv
    $('[ibcpPV="PV-WeighResult"]').each(function () {
        var $this = $(this);
        ibcpWeighResult.init($this);
    });

    //单选按钮组
    $('[ibcpPV="PV-SingleCheck"]').each(function () {
        var $this = $(this);
        ibcpSingleCheck.init($this);
    });

    $('[ibcpPV="PV-DeviationResult"]').each(function(){
        var $this = $(this);
        ibcpDeviationResult.init($this);
    });
  };

  //重置 pv 块 的样式
  var ResetStyle = function () {
    $('[ibcpBlock]').each(function () {
      var $this = $(this);
      //批报告状态
      $this.removeClass('status-block').addClass('fixed-block');

    });
  }

  //给外部的接口
  return {
    Init: InitPV,
    ResetStyle: ResetStyle
  };
})();

/**
 * PV对象集合
 */
/****************************************************PV对象************************************************************/

//曲线 pv 处理器
;var ibcpChartPV = (function () {

  //初始化 页面加载根据不同的状态处理 本类型 pv
  function InitChart(pvElement) {
    var thisElement = pvElement;                                  //当前 pv 元素
    var chartStatus = thisElement.attr('status');               //当前 pv 的状态
    var pvPracticeId = thisElement.attr('pvPracticeId');       //pvId
    var chartType = thisElement.attr('type');                   //曲线pv 类型 1:曲线图 2:按钮弹出式

    var ichart = new ibcpChart();                              //曲线数据处理对象

    //曲线图 处理
    if (chartType == 1) {
      var chartContainer = thisElement.find('.chartContainer');
      var dataBtn = thisElement.find('button.chartBtn');      //查看数据的按钮
      if (chartStatus <= 2) {
        ichart.Example(chartContainer);
        // dataBtn.css('visibility', 'hidden');
      }
      else {
        ichart.Show(chartContainer, pvPracticeId, chartStatus);
        // dataBtn.css('visibility', 'hidden');
      }
    }

    //按钮 处理
    if (chartType == 2) {
      var btn = thisElement.find('button.chartBtn');      // 寻找当前元素下的 chart 按钮 -- 查看数据
      if (chartStatus <= 2) {
        btn.attr('disabled', 'disabled');
      }
      else {
        btn.removeAttr('disabled');
        btn.on('click', function () {
          var title = '曲线分析图';
          var divIndex = 0;
          var url = path + '/WebUI/PV/Chart/Chart.html?pvPracticeId='
              + pvPracticeId + '&status=' + chartStatus;
          divIndex = ibcpLayer.ShowIframe(url, title, '800px', '600px', true);
        });
      }
    }
  };

  return {
    Init: InitChart
  };
})();

//ibcpChart 图表模块
var ibcpChart = (function () {
    var myChartContainer;       //用于显示曲线的容器
    var myPvPracticeId = -1;    //实际 pv 执行的Id
    var colors = ['blue', 'red', '#90ed7d', '#7cb5ec', '#f7a35c', '#434348',
        'D39DED', 'black'];
    var isOneY = true;
    var strTime;
    var endTime;
    var myStatus = 0;
    var timerFlag = 1;

    //图标示例 无数据 和 预览、未激活 时 使用
    var ExampleChart = function (chartContainer) {
        chartContainer.highcharts({
            chart: {
                // width : 1240,
                type: 'spline',
                //animation: Highcharts.svg, // don't animate in old IE
                marginRight: 10,
                zoomType: 'x',
                events: {
                    load: function () {
                        // var _this = this;
                        // var _con = _this.container;
                        // var _parent = $(_con).parents('div[ibcpshowpv]');
                        // var _timer = setInterval(function(){
                        //     var _w = _parent.width();
                        //     if(_w > 0){
                        //         chartContainer.highcharts({
                        //             chart : {
                        //                 width : _w
                        //             }
                        //         });
                        //         window.clearInterval(_timer);
                        //     }
                        // },1000);
                    }
                }
            },
            plotOptions: {
                //为 spline 曲线 定制样式
                spline: {
                    lineWidth: 2,                   //曲线宽度
                    states: {                       //形态
                        hover: {
                            lineWidth: 3            //鼠标悬浮在线上的 样式
                        }
                    },
                    marker: {
                        enabled: false              //线上是否有凸点
                    }
                },
                series: {
                    animation: false         //曲线是否动画
                }
            },
            credits: {enabled: false},     //不显示highchart商标
            legend: {                         //图例
                align: "center",             //程度标的目标地位
                verticalAlign: "top",       //垂直标的目标地位
                x: 0, //间隔x轴的间隔
                y: 20 //间隔Y轴的间隔
            },
            title: {
                text: '示例'
            },

            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                labels: {
                    formatter: function () {
                        return Highcharts.dateFormat('%H:%M', this.value.toFixed(2));
                    }
                },
                plotLines: [
                    {   //一条延伸到整个绘图区的线，标志着轴中一个特定值。
                        color: '#000',
                        dashStyle: 'dot', //Dash,Dot,Solid,默认Solid
                        width: 1,
                        value: 1493290421000,  //x轴显示位置，一个标记为1 - 1493289821000
                        label: {
                            rotation: 0,
                            color: 'green',
                            y: 15,
                            text: 'S',
                            style: {
                                fontStyle: 'italic',
                                color: 'green'
                            }
                        },
                        zIndex: 3
                    },
                    {
                        color: 'black',
                        dashStyle: 'dot',
                        width: 1,
                        value: 1493296421000,
                        label: {
                            rotation: 0,
                            color: 'red',
                            y: 15,
                            style: {
                                fontStyle: 'italic',
                                color: 'red'
                            },
                            text: 'E'
                        },
                        zIndex: 3
                    }
                ]
            },
            yAxis: [
                {
                    lineWidth: 1,
                    color: 'red',
                    tickColor: 'red',
                    title: {
                        text: '压差(N)/真空度(Pa)'
                    },
                    plotLines: [
                        {   //一条延伸到整个绘图区的线，标志着轴中一个特定值。
                            color: 'red',
                            dashStyle: 'Dash', //Dash,Dot,Solid,默认Solid
                            width: 1,
                            value: 120,  //y轴显示位置
                            zIndex: 5
                        },
                        {   //一条延伸到整个绘图区的线，标志着轴中一个特定值。
                            color: 'red',
                            dashStyle: 'Dash', //Dash,Dot,Solid,默认Solid
                            width: 1,
                            value: -80,  //y轴显示位置
                            zIndex: 5
                        },
                        {   //一条延伸到整个绘图区的线，标志着轴中一个特定值。
                            color: 'blue',
                            dashStyle: 'Dash', //Dash,Dot,Solid,默认Solid
                            width: 1,
                            value: 60,  //y轴显示位置
                            zIndex: 5,
                            label: {            //辅助线的标签描述
                                rotation: 0,    //字体是 旋转度
                                x: -10,            //文字开始 距离辅助线 左->右 的距离
                                y: 5,           //文字底部 距离辅助线 上->下 的距离
                                style: {        //辅助线标签描述的字体样式
                                    fontStyle: '宋体',
                                    color: 'blue'
                                },
                                text: '60'
                                //text: '下限:2'    //标签文本
                            },
                        },
                        {   //一条延伸到整个绘图区的线，标志着轴中一个特定值。
                            color: 'blue',
                            dashStyle: 'Dash', //Dash,Dot,Solid,默认Solid
                            width: 1,
                            value: 70,  //y轴显示位置
                            zIndex: 5,
                            label: {
                                rotation: 0,
                                x: -10,
                                y: 5,
                                style: {
                                    fontStyle: '宋体',
                                    color: 'blue'
                                },
                                text: '70'
                                //text: '上限:10'
                            },
                        }
                    ]
                }
            ],
            tooltip: {
                crosshairs: true,
                shared: true,
                xDateFormat: '时间：%Y-%m-%d %H:%M:%S'
            },
            //是否显示打印报表选项 默认 true
            exporting: {
                enabled: true
            },
            series: [
                {
                    name: '真空度',
                    color: 'red',
                    yAxis: 0,
                    data: (function () {
                        var data = [];
                        var yData = [-1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            -1,
                            1,
                            1,
                            1,
                            1,
                            6.89460001,
                            14.89619999,
                            25,
                            27.89200001,
                            30,
                            31.88942212,
                            34.88660002,
                            37,
                            40.88402321,
                            44.88460002,
                            48.88382322,
                            53,
                            57.87940001,
                            63,
                            68.87714742,
                            74.87522494,
                            81.7456509,
                            88.74320002,
                            93.87075508,
                            90.86760001,
                            93.8654269,
                            90.67000008,
                            95.86459999,
                            93.58660007,
                            86.86259999,
                            87.55359993,
                            90.28657075,
                            84.29040003,
                            86.27014594,
                            89.29714059,
                            84.39384253,
                            82,
                            82,
                            82.15376925,
                            83,
                            85.31680002,
                            89.88862238,
                            83,
                            83.16320414,
                            88.65333868,
                            82.16796639,
                            85.51649672,
                            82,
                            85.17456507,
                            82,
                            89.12017588,
                            82,
                            81.18089146,
                            82,
                            81.18428941,
                            85.54769051,
                            82,
                            81,
                            82,
                            81,
                            87,
                            81,
                            81,
                            83.39832034,
                            81,
                            80,
                            79,
                            81.20371852,
                            80,
                            79,
                            78,
                            85.26960011,
                            79,
                            79,
                            78,
                            89.21775645,
                            91,
                            90.77859998,
                            90.55240002,
                            90.22379999,
                            91,
                            90.77084585,
                            90,
                            90,
                            91,
                            90.52588443,
                            90,
                            90,
                            87.24235151,
                            75.24495099,
                            65.246,
                            56.24735053,
                            31.99900022,
                            6.754049183,
                            -21.24550184,
                            -42.49000798,
                            -56.4857143,
                            -65.7406075,
                            -66,
                            -71,
                            -74.73225355,
                            -77,
                            -79,
                            -80,
                            -81,
                            -79,
                            -77,
                            -74,
                            -73.16076788,
                            -78,
                            -79.71537077,
                            -81,
                            119.4516773,
                            114,
                            112.2922831,
                            111,
                            112,
                            111,
                            114,
                            110.3019584,
                            113,
                            111.6945222,
                            113.388334,
                            111,
                            111.311,
                            112.6838529,
                            112,
                            111,
                            112.6804639,
                            111.6788,
                            112.2808001,
                            113.3557289,
                            114.6492,
                            111.6723277,
                            114.0071986,
                            114.0077938,
                            111.3373976,
                            114.3186725,
                            112.3735758,
                            110.6552,
                            114.6538077,
                            112.3482,
                            112.2997602,
                            114.3508,
                            111,
                            113.9398361,
                            94.77322683,
                            54.79056762,
                            23.07700005,
                            7.445021971,
                            10.43659987,
                            7.367799997,
                            9.262147548,
                            8.889022181,
                            7.627372634,
                            9,
                            6.243156839,
                            10.24295144,
                            8.619399977,
                            8.617153135,
                            7.385414575,
                            9.065773692,
                            8.612232651,
                            9.824235113,
                            9.606678657,
                            9,
                            9.603879229,
                            9.602558982,
                            8,
                            9.196760597,
                            7.596199989,
                            7.223755244,
                            9.179764027,
                            6.414317148,
                            9.415516897,
                            8.165999985,
                            8.165366957,
                            6.739052172,
                            6.840631885,
                            7.117000103,
                            9.421999979,
                            8.425400019,
                            8.573485317,
                            9.1454836,
                            6.571600008,
                            7,
                            7.298140411,
                            7.181999922,
                            8.438712265,
                            8.239552084,
                            6.884938075,
                            7.770845846,
                            8.556865881,
                            9.215999985,
                            5.553999996,
                            7.797240561,
                            6.641271728,
                            6.354974035,
                            7.907999992,
                            8.628674237,
                            6.373400021,
                            9.086400032,
                            7.541891637,
                            8.920431828,
                            7,
                            7.845292887,
                            7.611277756,
                            9,
                            6.598360679,
                            0.469199991,
                            -1,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0
                        ];
                        var i;
                        for (i = 0; i < yData.length; i += 1) {
                            data.push({
                                x: 1493289821000 + i * 1000,
                                y: yData[i].toFixed(2) * 1
                            });
                        }
                        return data;
                    }())
                },
                {
                    name: '压差',
                    color: 'blue',
                    yAxis: 0,
                    data: (function () {
                        var data = [];
                        var yData = [66.23189271,
                            68.35396743,
                            65.00653264,
                            61.06245381,
                            68.34024794,
                            65.58211017,
                            68.36089843,
                            68.4212683,
                            67.65135711,
                            68.51490021,
                            68.51490021,
                            67.52219126,
                            68.51490021,
                            66.44489562,
                            67.31290091,
                            66.89651351,
                            67.31556557,
                            67.16518777,
                            67.34624048,
                            68.51490021,
                            67.01916619,
                            68.51490021,
                            66.28801362,
                            65.44113403,
                            65.7501131,
                            64.899209,
                            66.01061638,
                            66.08169825,
                            66.38660688,
                            67.35439542,
                            66.77461998,
                            67.54629679,
                            65.32708277,
                            68.51490021,
                            68.51490021,
                            68.24873774,
                            66.31232438,
                            66.35790489,
                            66.52941829,
                            67.07964812,
                            65.34673628,
                            65.29113408,
                            65.60503162,
                            65.74555365,
                            63.26997931,
                            64.70725292,
                            67.73449756,
                            66.70801892,
                            65.95358709,
                            65.19582291,
                            67.16881712,
                            64.93057945,
                            66.7235105,
                            65.75239351,
                            65.83426387,
                            65.59108153,
                            68.23130603,
                            65.49225278,
                            68.51490021,
                            67.02453094,
                            66.99754141,
                            66.16832636,
                            64.48211793,
                            64.17483807,
                            64.85840032,
                            64.64207037,
                            65.34830988,
                            66.40320875,
                            66.58233021,
                            64.89700775,
                            65.15294434,
                            64.77949632,
                            64.9325597,
                            65.03853534,
                            65.80146887,
                            66.78150611,
                            66.130552,
                            66.01477474,
                            68.29856474,
                            67.1483761,
                            65.85636895,
                            66.11110414,
                            66.29608217,
                            66.19401662,
                            64.67264298,
                            65.02834313,
                            64.37714965,
                            65.21782027,
                            66.30719768,
                            66.08179952,
                            67.63680954,
                            65.62897133,
                            65.10416412,
                            65.28834916,
                            64.48218407,
                            64.72276494,
                            64.56397813,
                            65.80404088,
                            63.60621204,
                            64.44383849,
                            64.99652569,
                            64.35957507,
                            65.28361354,
                            63.61051334,
                            63.60545125,
                            66.2019498,
                            66.32360749,
                            64.67882666,
                            65.24924343,
                            65.47461235,
                            65.19651393,
                            64.83650889,
                            66.01190099,
                            65.81439484,
                            64.61251919,
                            65.6326605,
                            66.05239688,
                            67.85927188,
                            65.96855932,
                            66.55927122,
                            66.95084607,
                            64.671006,
                            66.2499246,
                            67.44635521,
                            67.64219322,
                            67.04115733,
                            67.58601305,
                            68.17535767,
                            67.67556293,
                            66.96175884,
                            68.51490021,
                            66.34508561,
                            67.87330556,
                            67.17464326,
                            66.400312,
                            67.1590196,
                            67.17114223,
                            66.02042085,
                            66.53421603,
                            65.56205227,
                            66.7574902,
                            66.19902653,
                            66.11564527,
                            66.28729362,
                            67.05173107,
                            65.6668862,
                            66.31517144,
                            65.80250006,
                            64.67620285,
                            65.63595652,
                            65.86459446,
                            66.16121153,
                            66.59244546,
                            66.35378246,
                            66.68740676,
                            66.10789093,
                            64.79366421,
                            66.92296146,
                            66.66513855,
                            65.33109889,
                            64.61633683,
                            65.65631612,
                            66.15256656,
                            65.1753367,
                            66.12427605,
                            66.65273023,
                            65.74235797,
                            66.7006005,
                            66.17702415,
                            66.31085954,
                            67.11939324,
                            67.90970906,
                            68.51490021,
                            68.51490021,
                            68.51490021,
                            68.51490021,
                            68.51490021,
                            68.51490021,
                            67.44614588,
                            66.84179179,
                            66.37865469,
                            66.9087218,
                            68.51490021,
                            67.79183664,
                            66.94648207,
                            67.33185919,
                            66.91147913,
                            67.95168368,
                            68.51490021,
                            66.04214352,
                            67.83108782,
                            67.58732716,
                            67.31994385,
                            66.18612176,
                            65.82794978,
                            66.7623369,
                            67.86473397,
                            67.31747424,
                            68.51490021,
                            66.67348936,
                            66.70834246,
                            65.84036839,
                            65.98198732,
                            65.42194079,
                            60.73772555,
                            64.37168,
                            65.80348238,
                            66.40293096,
                            64.47746307,
                            65.43616725,
                            66.11487211,
                            66.30057717,
                            65.22002729,
                            64.92775594,
                            65.48529982,
                            64.48577895,
                            65.79860687,
                            65.74643075,
                            65.75852951,
                            65.86338644,
                            64.94469443,
                            64.1610617,
                            66.50163976,
                            66.88937536,
                            67.92175857,
                            67.8871103,
                            68.51490021,
                            67.92871323,
                            66.70595957,
                            67.78985113,
                            66.90339413,
                            67.00090983,
                            66.47930344,
                            65.82021645,
                            65.85588876,
                            65.35951335,
                            65.7994959,
                            66.33882889,
                            65.54987603,
                            66.93309014,
                            66.11221102];
                        var i;
                        for (i = 0; i < yData.length; i += 1) {
                            data.push({
                                x: 1493289821000 + i * 1000,
                                y: yData[i].toFixed(2) * 1
                            });
                        }
                        return data;
                    }())
                }
            ]
        });
    }

    /**
     * 显示曲线
     * @param chartContainer        用于显示曲线的容器
     * @param orderId               批指令Id
     * @param workCenterOrderId     工位指令Id
     * @param practiceStepId        实际步骤Id
     * @param stepId                步骤Id
     * @constructor
     */
    var ShowChart = function (chartContainer, pvPracticeId, status) {
        myStatus = status;
        if (myStatus <= 2) {
            ExampleChart(chartContainer);
            return;
        }
        //缓存参数
        myChartContainer = chartContainer;
        myPvPracticeId = pvPracticeId;

        //获取数据的Url
        var dataUrl = serverPath + 'pv/getCurveData';
        //获取数据的参数
        var params = {
            'pvPracticeId': myPvPracticeId
        };

        //获取 后台 数据
        ibcpAjax.Select(dataUrl, params, true, function (resultData) {
            var chartData = JSON.parse(resultData.data);      //曲线数据

            strTime = chartData.stepStartTime;    //开始
            endTime = chartData.stepEndTime;      //结束
            isOneY = chartData.oneY;            //是否一条Y轴

            var phaseName = chartData.name;       //阶段名
            var phase = chartData.event;              //阶段 开始-结束 时间点 数据集合
            var tags = chartData.tags;                //曲线数据 集合
            var title = strTime + ' -- ' + endTime;
            var yAxis = GetYAxis(tags);
            var xAxis = GetXAxis(phase);
            var series = GetSeries(tags);
            SetChartData(title, xAxis, yAxis, series);
        });

    }

    //设置 chart 数据
    function SetChartData(title, xAxis, yAxis, series) {
        myChartContainer.highcharts({
            chart: {
                type: 'spline',
                //animation: Highcharts.svg, // don't animate in old IE
                marginRight: 10,
                zoomType: 'x',
                events: {
                    selection: function (e) {
                        // 事件处理代码，可以通过 console.log(e) 查看更多详细信息
                        var start = 0;
                        var end = 0;
                        if (e.xAxis) {
                            console.log(new Date(e.xAxis[0].min));
                            console.log(new Date(e.xAxis[0].max));
                            start = e.xAxis[0].min;
                            end = e.xAxis[0].max;
                            timerFlag = 0;
                        }
                        else {
                            console.log(new Date(e.target.xAxis[0].dataMin));
                            console.log(new Date(e.target.xAxis[0].dataMax));
                            start = e.target.xAxis[0].dataMin;
                            end = e.target.xAxis[0].dataMax;
                            timerFlag = 1;
                        }
                        var params = {'startTime': start, 'endTime': end};
                        ibcpPVExecute.UpdatePV(myPvPracticeId, 'Chart',
                            JSON.stringify(params), function (result) {
                            });
                    },
                    load: function () {
                        var c = this.container;
                        $(c).css('width', '');
                        $(c).css('height', '');
                        //曲线加载完成后的 自定义处理内容 周期刷数据
                        if (myStatus == 3) {
                            var myChart = this;
                            var myTitle = {text: ''};
                            var series = myChart.series;
                            setInterval(function () {
                                if (timerFlag == 1) {
                                    // console.log('刷新曲线:' + endTime);
                                    var reUrl = serverPath + 'pv/getCurveCurrent';
                                    var reParam = {
                                        'pvPracticeId': myPvPracticeId,
                                        'strTime': endTime
                                    };
                                    ibcpAjax.Select(reUrl, reParam, true, function (resultData) {
                                        var chartData = JSON.parse(resultData.data);      //曲线数据
                                        // console.log('数据：'+chartData);
                                        endTime = chartData.stepEndTime;      //更新结束时间
                                        // console.log('数据结束时间：'+endTime);
                                        var tags = chartData.tags;                //曲线数据 集合
                                        myTitle.text = strTime + ' -- ' + endTime;

                                        //遍历线
                                        var lineNum = series.length;
                                        // console.log('线的数目：'+lineNum);
                                        for (var i = 0; i < lineNum; i++) {
                                            var s = series[i];
                                            var lineName = s.name;
                                            //遍历tags 数据
                                            for (var t = 0; t < tags.length; t++) {
                                                var tag = tags[t];
                                                var tName = tag.name + '(' + tag.unit + ')';
                                                if (lineName == tName) {
                                                    var addData = ConvertData(tag.data);
                                                    // //循环单个添加点
                                                    var dNum = addData.length;
                                                    // console.log('第'+ i +'条线 数据：'+ addData);
                                                    for (var j = 0; j < dNum; j++) {
                                                        var pData = addData[j];
                                                        s.addPoint([pData.x, pData.y], false, false);
                                                    }
                                                }
                                            }
                                        }

                                        //重置标题
                                        myChart.setTitle(myTitle);

                                        //添加事件信号辅助线
                                        var phase = chartData.event;
                                        // var oldPLs = myChart.xAxis[0].plotLinesAndBands[0].options.value;
                                        var oldPLs = myChart.xAxis[0].plotLinesAndBands;
                                        // console.log('已有的事件信息：'+ oldPLs.length);
                                        // console.log('事件信息：'+ phase.length);

                                        for (var i = 0; i < phase.length; i++) {
                                            var oneSE = phase[i];
                                            //时间需要转换
                                            var str = oneSE.newStartTime;
                                            // console.log('事件开始：'+ str);
                                            if (str != '') {
                                                try {
                                                    str = (new Date(str)).getTime();    //转成毫秒时间
                                                    var has = false;
                                                    //遍历是否已处理信号点
                                                    for (var p = oldPLs.length - 1; p >= 0; p--) {
                                                        if (oldPLs[p].options.value == str) {
                                                            has = true;
                                                            // console.log('重复：'+ str);
                                                            break;
                                                        }
                                                    }
                                                    //没有重复则添加
                                                    if (!has) {
                                                        var strPlot = CreatXPlotLine('green', str, 'S');
                                                        myChart.xAxis[0].addPlotLine(strPlot);
                                                        // console.log('添加：'+ str);
                                                    }
                                                } catch (e) {
                                                    console.log('曲线刷新阶段-开始：' + e);
                                                }
                                            }

                                            var end = oneSE.newEndTime;

                                            // console.log('事件结束：'+ end);
                                            if (end != '') {
                                                try {
                                                    end = (new Date(end)).getTime();    //转成毫秒时间
                                                    var has = false;
                                                    //遍历是否已处理信号点
                                                    for (var p = oldPLs.length - 1; p >= 0; p--) {
                                                        if (oldPLs[p].options.value == end) {
                                                            has = true;
                                                            // console.log('重复：'+ end);
                                                            break;
                                                        }
                                                    }
                                                    //没有重复则添加
                                                    if (!has) {
                                                        var endPlot = CreatXPlotLine('red', end, 'E');
                                                        myChart.xAxis[0].addPlotLine(endPlot);
                                                        // console.log('添加：'+ end);
                                                    }
                                                } catch (e) {
                                                    console.log('曲线刷新阶段-结束：' + e);
                                                }
                                            }
                                        }
                                    }, true);
                                    myChart.redraw();                   //重绘
                                }
                            }, 3000);
                        }
                    }
                }
            },
            plotOptions: {
                //为 spline 曲线 定制样式
                spline: {
                    lineWidth: 2,                   //曲线宽度
                    states: {                       //形态
                        hover: {
                            lineWidth: 2.7            //鼠标悬浮在线上的 样式
                        }
                    },
                    marker: {
                        enabled: false              //线上是否有凸点
                    }
                },
                series: {
                    enableMouseTracking: false,
                    shadow: false,
                    animation: false         //曲线是否动画
                }
            },
            credits: {enabled: false},     //不显示highchart商标
            legend: {                         //图例
                align: "center",             //程度标的目标地位
                verticalAlign: "top",       //垂直标的目标地位
                x: 0, //间隔x轴的间隔
                y: 20 //间隔Y轴的间隔
            },
            title: {
                text: title
            },
            xAxis: xAxis,
            yAxis: yAxis,
            tooltip: {
                crosshairs: true,
                shared: true,
                //valueSuffix : ' kg',
                xDateFormat: '时间：%Y-%m-%d %H:%M:%S'
            },
            //是否显示打印报表选项 默认 true
            exporting: {
                enabled: false
            },
            series: series
        });
    }

    //测试曲线数据
    function TestData() {
        var tData = [];
        //x上限，y下限
        var max = 28;
        var min = 12;
        //var strTime = (new Date()).getTime();
        var strTime = 1493289821000;
        //60秒一个点  1小时=60个
        for (var i = 0; i < 60; i += 1) {
            var yVal = (Math.random() * (max - min + 1) + min).toFixed(2) * 1;
            tData.push({
                x: strTime + i * 1000 * 60,
                y: yVal
            });
        }
        return tData;
    }

    //得到 x 轴
    function GetXAxis(phase) {
        var xPlotLines = [];
        xPlotLines = GetXPlotLines(phase);
        var xAxis = {
            type: 'datetime',
            //tickPixelInterval: 150,
            labels: {
                formatter: function () {
                    return Highcharts.dateFormat('%H:%M', this.value);
                }
            },
            plotLines: xPlotLines
        };
        return xAxis;
    }

    //创建 基于 x 轴的 所有辅助线
    function GetXPlotLines(phase) {
        var xPlotLines = [];
        var pCount = phase.length;
        for (var i = 0; i < pCount; i++) {
            var oneSE = phase[i];

            //时间需要转换
            var str = oneSE.newStartTime;
            if (str != '') {
                try {
                    str = StringDateToIntDate(str);    //转成毫秒时间
                    var strPlot = CreatXPlotLine('green', str, 'S');
                    xPlotLines.push(strPlot);
                } catch (e) {
                    console.log(e);
                }
            }

            var end = oneSE.newEndTime;
            if (end != '') {
                try {
                    end = StringDateToIntDate(end);    //转成毫秒时间
                    var endPlot = CreatXPlotLine('red', end, 'E');
                    xPlotLines.push(endPlot);
                } catch (e) {
                    console.log(e);
                }
            }
        }
        return xPlotLines;
    }

    //创建 一条基于 x 轴的辅助线
    function CreatXPlotLine(pColor, val, mark) {
        var xPlotLine = {   //一条延伸到整个绘图区的线，标志着轴中一个特定值。
            color: pColor,
            dashStyle: 'dot', //Dash,Dot,Solid,默认Solid
            width: 1,
            value: val,  //x轴显示位置
            label: {
                rotation: 0,
                color: pColor,
                y: 15,
                text: mark,
                style: {
                    fontStyle: 'italic',
                    color: pColor
                }
            },
            zIndex: 3
        }
        return xPlotLine;
    }

    //创建数据线
    function GetSeries(tags) {
        var series = [];
        for (var i = 0; i < tags.length; i++) {
            var tag = tags[i];
            var lineName = tag.name + '(' + tag.unit + ')';
            var lColor = colors[i];
            var yIndex = i;
            var data = ConvertData(tag.data);
            if (isOneY) {
                yIndex = 0;
            }
            var line = CreatLine(lineName, lColor, yIndex, data);
            series.push(line);
        }
        return series;
    }

    //标准时间字符串 转 时间的数字 毫秒数
    function StringDateToIntDate(dateStr) {
        //拆分时间
        var arr = dateStr.split(/[- :]/);
        //按 - ：拆分时间 年 月 日 时 分 秒 重新构建日期对象
        var data = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
        //时间转毫秒
        var intData = data.getTime();
        return intData;
    }

    /**
     * 转换数据
     * @param reData
     * @returns {Array}
     * @constructor
     */
    function ConvertData(reData) {
        var tData = [];
        if (reData != null) {
            for (var i = 0; i < reData.length; i += 1) {
                var xVal = reData[i].timestamp;
                xVal = StringDateToIntDate(xVal);
                var yVal = reData[i].value;
                yVal = parseFloat(yVal);
                tData.push({
                    x: xVal,
                    y: yVal
                });
            }
        }
        return tData;
    }

    //创建一条数据线
    function CreatLine(name, lColor, yIndex, data) {
        var line = {
            name: name,
            color: lColor,
            yAxis: yIndex,
            data: data
        }
        return line;
    }

    //创建 y 轴
    function GetYAxis(tags) {
        var yAxis = [];
        var yCount = tags.length;
        if (yCount > 0) {
            if (yCount == 1) {
                var y = CreatY(tags[0], colors[0]);
                yAxis.push(y);
                return yAxis;
            }
            else {
                if (isOneY) {
                    var y = CreatOneY(tags);
                    yAxis.push(y);
                    return yAxis;
                } else {
                    for (var i = 0; i < yCount; i++) {
                        var y = CreatY(tags[i], colors[i]);
                        yAxis.push(y);
                    }
                    return yAxis;
                }
            }

        }
        return yAxis;
    }

    //创建 数据对应的单条 y 轴 包括 辅助线
    function CreatY(tag, sColor) {
        var yTitle = tag.name + '(' + tag.unit + ')';
        //本条 y 轴 的辅助线 -- 上下限
        var yPlotLines = [];
        if (tag.warnMax != 'N/A') {
            var plotLine = CreatYPlotLine(sColor, tag.warnMax * 1);
            yPlotLines.push(plotLine);
        }
        if (tag.warnMin != 'N/A') {
            var plotLine = CreatYPlotLine(sColor, tag.warnMin * 1);
            yPlotLines.push(plotLine);
        }
        if (tag.devMax != 'N/A') {
            var plotLine = CreatYPlotLine(sColor, tag.devMax * 1);
            yPlotLines.push(plotLine);
        }
        if (tag.devMin != 'N/A') {
            var plotLine = CreatYPlotLine(sColor, tag.devMin * 1);
            yPlotLines.push(plotLine);
        }
        //组建 y 轴
        var yZhou = {
            lineWidth: 1,
            color: sColor,
            tickColor: sColor,
            title: {
                color: sColor,
                text: yTitle
            },
            plotLines: yPlotLines
        };
        return yZhou;
    }

    //多数据单一 y 轴
    function CreatOneY(tags) {
        var tagCount = tags.length;
        var yPlotLines = [];
        for (var i = 0; i < tagCount; i++) {
            var tag = tags[i];
            var plotColor = colors[i];
            if (tag.max != '未设置检查项') {
                var plotMax = CreatYPlotLine(plotColor, tag.max);
                yPlotLines.push(plotMax);
            }
            if (tag.min != '未设置检查项') {
                var plotMin = CreatYPlotLine(plotColor, tag.min);
                yPlotLines.push(plotMin);
            }
        }
        var yAxis = {
            tickColor: colors[0],
            title: {
                text: ''
            },
            plotLines: yPlotLines
        };
        return yAxis;
    }

    //创建一条基于 y 轴的辅助线
    function CreatYPlotLine(pColor, val) {
        var plotLine = {
            //一条延伸到整个绘图区的线，标志着轴中一个特定值。
            color: pColor,
            dashStyle: 'Dash', //Dash,Dot,Solid,默认Solid
            width: 1,
            value: val,  //y轴显示位置
            zIndex: 5,
            label: {            //辅助线的标签描述
                rotation: 0,    //字体是 旋转度
                x: -10,          //文字开始 距离辅助线 左->右 的距离
                y: 5,           //文字底部 距离辅助线 上->下 的距离
                style: {        //辅助线标签描述的字体样式
                    fontStyle: '宋体',
                    color: pColor
                },
                text: val       //标签文本
            }
        };
        return plotLine;
    }

    //给外部的接口
    return {
        Example: ExampleChart,
        Show: ShowChart
    };

});

/**
 *@description:单选按钮组
 *@author:tudecai
 */
var ibcpSingleCheck = (function () {

    //初始化单选按钮组
    function initSingleCheckGroup(pvElement) {
        var pvElem = pvElement;

        var pvval = pvElem.attr("pvval");
        if (pvval == "N/A") {
            return;
        }
        //根据值勾选对应项
        setCurrentCheck(pvElem, pvval);

    }

    //设置选择项
    function setCurrentCheck(pvElement, thisVal) {
        var checkIcon = pvElement.find("checkIcon");

        $.each(checkIcon, function (i, elem) {
            var val = $(elem).attr("val");

            if (val == thisVal) {
                pvElement.attr("pvval", val);
                pvElement.find(".fa-check-square-o").attr("class",
                    "fa fa-square-o fa-lg");
                $(elem).attr("class", "fa fa-check-square-o fa-lg");
                return false;
            }
        })
    }

    return {
        init: initSingleCheckGroup
    }
})();

/**
 * 称量结果集PV
 * @type {{init}}
 */
var ibcpWeighResult = (function () {
    'use strict';
    var _buffer = {
        config: []
    };

    //初始化方法
    var init = function (pv) {
        pv.parent('span[ibcpshowpv="pvcon"]').css('width','100%');
        var pvPracticeId = pv.attr('pvPracticeId'),                     //pv实绩id
            bomItemNO = pv.attr('bomItemNo'),                           //bom项号
            status = pv.attr('status'),                                 //状态
            pvId = pv.attr('pvId'),                                     //pvId
            configPath = serverPath + 'pv/findPvById',                  //获取配置接口
            dataPath = serverPath + 'weighing/getWeighResultData';      //获取数据接口

        //组装查询数据调用接口上传数据
        var postData = {
            orderId: orderId,
            pvPracticeId: pvPracticeId,
            bomItemNO: bomItemNO
        };

        //定义表格
        var $table = $('<table class="bootstrap-table table"></table>');
        pv.append($table);

        //调用后端接口获取称量结果集表格配置数据
        ibcpAjax.Select(configPath, {'id': pvId}, true, function (result) {
            var param = JSON.parse(result.data.param);
            var _config = JSON.parse(param.config);
            var _tbConfig = [];
            //整理配置表格数据
            for (var i = 0; i < _config.length; i++) {
                //整理单元配置数据
                var cur = {
                    field: _config[i].code,
                    title: _config[i].name,
                    visible: _config[i].check
                };
                //将单元数据推入数组
                _tbConfig.push(cur);

                //将当前显示的列数据推入缓存配置中，将来用于合并单元格的检查
                _buffer.config.push(cur);
            }

            //表格加载列定义
            $table.bootstrapTable({
                columns: _tbConfig        //列配置定义
            });

            //给当前表格添加默认样式
            $table.removeClass('table-hover');              //移除鼠标hover行变色
            $table.addClass('ibcp-default-table');          //添加默认表格样式
            $table.addClass('ibcp-weigh-result-tb');        //添加称量结果表格样式

            _execute(dataPath, postData, status, $table);
        }, true);
    };

    //执行方法
    var _execute = function (dataPath, postData, status, table) {
        //执行中状态
        if (status == 3) {
            _loadDatas(dataPath, postData, table);
            var _timer = window.setInterval(function () {
                _loadDatas(dataPath, postData, table);
            }, 30000);
        }

        //执行完和已审核状态
        else if (status == 4 || status == 5) {
            _loadDatas(dataPath, postData, table);
        }
    };

    //处理并加载数据
    var _loadDatas = function (dataPath, postData, table, callback) {
        ibcpAjax.Select(dataPath, postData, true, function (result) {

            //获取数据信息
            var _datas = result.data;

            //加载数据到表格
            table.bootstrapTable('load', _datas);

            //遍历相同数据单元格合并
            for (var i = 0; i < _buffer.config.length; i++) {
                _mergeCells(_datas, _buffer.config[i].field, 1, table);
            }

            //执行回调
            if (typeof(callback) === 'function') {
                callback();
            }
        }, true);
    };

    /**
     * 合并单元格
     * @param data  原始数据（在服务端完成排序）
     * @param fieldName 合并属性名称
     * @param colspan   合并列
     * @param target    目标表格对象
     */
    function _mergeCells(data, fieldName, colspan, target) {
        //声明一个map计算相同属性值在data对象出现的次数和位置
        var sortMap = {};
        for (var i = 0; i < data.length; i++) {
            for (var prop in data[i]) {
                if (prop == fieldName) {
                    var key = data[i][prop]
                    if (sortMap.hasOwnProperty(key)) {
                        sortMap[key] = sortMap[key] * 1 + 1;
                    } else {
                        sortMap[key] = 1;
                    }
                    break;
                }
            }
        }
        for (var prop in sortMap) {
            console.log(prop, sortMap[prop])
        }
        var index = 0;
        for (var prop in sortMap) {
            var count = sortMap[prop] * 1;
            $(target).bootstrapTable('mergeCells',
                {index: index, field: fieldName, colspan: colspan, rowspan: count});
            index += count;
        }
    }

    return {
        init: init
    };
})();

/**
 * 偏差结果集PV
 */
var ibcpDeviationResult = (function(){
    'use strict';
    var _buffer = {
        config: []
    };

    //初始化方法
    var init = function (pv) {
        pv.parent('span[ibcpshowpv="pvcon"]').css('width', '100%');
        var pvPracticeId = pv.attr('pvPracticeId'),                     //pv实绩id
            status = pv.attr('status'),                                 //状态
            pvId = pv.attr('pvId'),                                     //pvId
            configPath = serverPath + 'pv/queryDeviationResultConfig',                  //获取配置接口
            dataPath = serverPath + 'pv/queryDeviationResultList';      //获取数据接口

        //组装查询数据调用接口上传数据
        var postData = {
            pvPracticeId: pvPracticeId
        };

        //定义表格
        var $table = $('<table class="bootstrap-table table"></table>');
        pv.append($table);

        //调用后端接口获取称偏差结果集表格配置数据
        ibcpAjax.Select(configPath, {'pvId': pvId}, true, function (result) {
            var _config = JSON.parse(result.data);
            var _tbConfig = [];
            //整理配置表格数据
            for (var i = 0; i < _config.length; i++) {
                //整理单元配置数据
                var cur = {
                    field: _config[i].code,
                    title: _config[i].name,
                    visible: _config[i].check
                };
                //将单元数据推入数组
                _tbConfig.push(cur);

                //将当前显示的列数据推入缓存配置中，将来用于合并单元格的检查
                _buffer.config.push(cur);
            }

            //表格加载列定义
            $table.bootstrapTable({
                columns: _tbConfig        //列配置定义
            });

            //给当前表格添加默认样式
            $table.removeClass('table-hover');              //移除鼠标hover行变色
            $table.addClass('ibcp-default-table');          //添加默认表格样式
            $table.addClass('ibcp-weigh-result-tb');        //添加称量结果表格样式

            _execute(dataPath, postData, status, $table);
        }, true);
    };

    //执行方法
    var _execute = function (dataPath, postData, status, table) {
        //执行中状态
        if (status == 3) {
            _loadDatas(dataPath, postData, table);
            var _timer = window.setInterval(function () {
                _loadDatas(dataPath, postData, table);
            }, 30000);
        }

        //执行完和已审核状态
        else if (status == 4 || status == 5) {
            _loadDatas(dataPath, postData, table);
        }
    };

    //处理并加载数据
    var _loadDatas = function (dataPath, postData, table, callback) {
        ibcpAjax.Select(dataPath, postData, true, function (result) {

            //获取数据信息
            var _datas = result.data;

            //加载数据到表格
            table.bootstrapTable('load', _datas);

            //遍历相同数据单元格合并
            // for (var i = 0; i < _buffer.config.length; i++) {
            //     _mergeCells(_datas, _buffer.config[i].field, 1, table);
            // }

            //执行回调
            if (typeof(callback) === 'function') {
                callback();
            }
        }, true);
    };

    /**
     * 合并单元格
     * @param data  原始数据（在服务端完成排序）
     * @param fieldName 合并属性名称
     * @param colspan   合并列
     * @param target    目标表格对象
     */
    function _mergeCells(data, fieldName, colspan, target) {
        //声明一个map计算相同属性值在data对象出现的次数和位置
        var sortMap = {};
        for (var i = 0; i < data.length; i++) {
            for (var prop in data[i]) {
                if (prop == fieldName) {
                    var key = data[i][prop]
                    if (sortMap.hasOwnProperty(key)) {
                        sortMap[key] = sortMap[key] * 1 + 1;
                    } else {
                        sortMap[key] = 1;
                    }
                    break;
                }
            }
        }
        for (var prop in sortMap) {
            console.log(prop, sortMap[prop])
        }
        var index = 0;
        for (var prop in sortMap) {
            var count = sortMap[prop] * 1;
            $(target).bootstrapTable('mergeCells',
                {index: index, field: fieldName, colspan: colspan, rowspan: count});
            index += count;
        }
    }

    return {
        init: init
    };
})();

/**********************************************************************************************************************/

var ibcpPV_Bot = (function () {

  var botInfo = {
    bots: [],
    botTotal: {
      botNo: '理瓶数量',
      botTimes: '0 盘(约 0 万支)',
      botNum: '损耗总数',
      botLose: '0 支',
      botBatch: '',
      botStart: '',
      botEnd: ''
    }
  };

  var thisElement = undefined;
  var botInit = function (pvElement) {
    thisElement = pvElement; // 当前元素
    var this_status = thisElement.attr('status');   //当前 pv 状态
    var pvPracticeId = thisElement.attr("pvPracticeId");
    var prop = thisElement.attr('prop');        //签名配置的 权限id
    var btnAdd = thisElement.find('.botAdd');        // 寻找当前元素下的新增按钮
    var btnDel = thisElement.find('.botDel');        // 寻找当前元素下的删除按钮
    var botTable = thisElement.find('.botTable');   // 寻找当前元素下的table

    if (this_status < 3) {
      bindBotTable(botTable);
    }
    else if (this_status == 3) {
      LoadBotInfo(botTable, pvPracticeId, prop);
      //添加
      btnAdd.click(function () {
        ibcpYSHbot.Add(pvPracticeId, prop, botInfo, function () {
          bindBotTable(botTable);
        })
      });
      //删除
      btnDel.click(function () {
        var delBot = botTable.bootstrapTable('getSelections')[0];
        var botNo = delBot.botNo;
        if (botNo != undefined && botNo != '' && botNo != '理瓶数量') {
          for (var i in  botInfo.bots) {
            if (botInfo.bots[i].botNo == botNo) {
              botInfo.bots.splice(i, 1);
              break;
            }
          }
          botInfo = ibcpYSHbot.ReSum(botInfo);
          ibcpYSHbot.Save(pvPracticeId, prop, botInfo, function () {
            bindBotTable(botTable);
          });
        }
      });
    }
    else {
      LoadBotPracInfo(botTable, pvPracticeId, prop);
    }

  }

  var setTableBorderStyle = function () {
    var tableContainer = thisElement.find(".fixed-table-container");
    tableContainer.css("border-width", "0px");
  }

  var LoadBotInfo = function (botTable, pvPracticeId, prop) {
    var url = serverPath + 'tagValue/getPvValue';
    var params = {'pvPracticeId': pvPracticeId, 'prop': prop};
    ibcpAjax.Select(url, params, true, function (result) {
      var reBot = result.data.pvVal;
      if (reBot != 'N/A') {
        botInfo = reBot;
      }
      bindBotTable(botTable);
    }, true);
  }

  var bindBotTable = function (botTable) {
    var nowBots = $.extend(true, [], botInfo.bots); //产生新的数据源
    nowBots.push(botInfo.botTotal);
    botTable.bootstrapTable('load', nowBots);
    setTableBorderStyle();
    botTable.tableHideCheckbox();

  }

  var LoadBotPracInfo = function (botTable, pvPracticeId, prop) {
    var url = serverPath + 'pv/findPvValue';
    var params = {'pvPracticeId': pvPracticeId, 'prop': prop};
    ibcpAjax.Select(url, params, true, function (result) {
      var reBot = result.data.val;
      if (reBot != 'N/A' && reBot != '' && reBot != null && reBot
          != undefined) {
        botInfo = reBot;
      }
      bindBotTable(botTable);
    }, true);
  }

  return {
    Init: botInit
  }
})();

//理瓶操作
var ibcpYSHbot = (function () {

  var divIndex = 0;
  var botAdd = function (pvPracticeId, prop, botInfo, callBack) {

    var htmlUrl = getRootPath() + '/WebUI/PV/Bottle/Bot_Add.html';
    divIndex = ibcpLayer.ShowDiv(htmlUrl, '新增理瓶', '400px', '400px',
        function () {
          var botStart;
          var botEnd;
          // 控制结束时间输入
          $("#botEnd").attr("disabled", true);
          // 选择开始时间
          $("#botStart").on("click", function () {
            botStart = $("#botStart").val();
            botEnd = $("#botEnd").val();
            ibcpDateTime.DateTime(botStart, "", function (data) {
              // 返回数据
              $("#botStart").val(data);
              // 结束时间可选
              $("#botEnd").attr("disabled", false);
            });
          });
          // 选择结束时间
          $("#botEnd").on("click", function () {
            botStart = $("#botStart").val();
            botEnd = $("#botEnd").val();
            ibcpDateTime.DateTime(botEnd, botStart, function (data) {
              // 返回数据
              $("#botEnd").val(data);
            });
          });

          $('#btnBotAddOK').click(function () {
            var bot = {
              botNo: '',
              botTimes: '',
              botNum: '',
              botLose: '',
              botBatch: '',
              botStart: '',
              botEnd: ''
            };
            bot.botNo = $('#botNo').val();
            bot.botStart = $('#botStart').val();
            bot.botEnd = $('#botEnd').val();
            bot.botNum = $('#botNum').val();
            bot.botLose = $('#botLose').val();
            bot.botBatch = $('#botBatch').val();

            if (bot.botNo == '') {
              ibcpLayer.ShowTips('请输入', $('#botNo'));
              return;
            }
            if (bot.botStart == '') {
              ibcpLayer.ShowTips('请输入', $('#botStart'));
              return;
            }
            if (bot.botEnd == '') {
              ibcpLayer.ShowTips('请输入', $('#botEnd'));
              return;
            }
            if (bot.botNum == '') {
              ibcpLayer.ShowTips('请输入', $('#botNum'));
              return;
            }
            if (bot.botLose == '') {
              ibcpLayer.ShowTips('请输入', $('#botLose'));
              return;
            }
            if (bot.botBatch == '') {
              ibcpLayer.ShowTips('请输入', $('#botBatch'));
              return;
            }

            bot.botTimes = bot.botStart.substring(11, 16) + ' 至 '
                + bot.botEnd.substring(11, 16);
            botInfo.bots.push(bot);
            botInfo = ReSumBots(botInfo);
            SaveBots(pvPracticeId, prop, botInfo, function () {
              ibcpLayer.Close(divIndex);
              if (callBack) {
                callBack();
              }
            });
          });

          $('#btnBotAddCancel').click(function () {
            ibcpLayer.Close(divIndex);
          });
        });
  }

  //重计算
  var ReSumBots = function (botInfo) {
    var bots = botInfo.bots;
    var sumPan = 0;
    var sumLose = 0;
    for (var i = 0; i < bots.length; i++) {
      var bot = bots[i];
      sumPan += bot.botNum * 1;
      sumLose += bot.botLose * 1;
    }
    var zhi = (sumPan * 750 / 10000).toFixed(2);
    botInfo.botTotal.botTimes = sumPan + ' 盘(约 ' + zhi + ' 万支)';
    botInfo.botTotal.botLose = sumLose + ' 支';
    return botInfo;
  }

  //保存方法
  var SaveBots = function (pvPracticeId, prop, botInfo, callBack) {
    var url = serverPath + 'tagValue/savePvValue';
    var params = {
      'pvPracticeId': pvPracticeId,
      'prop': prop,
      'botInfo': JSON.stringify(botInfo)
    };
    ibcpAjax.Insert(url, params, true, function (result) {
      ibcpLayer.ShowOK('完成');
      if (callBack) {
        callBack();
      }
    }, true);
  }

  return {
    Add: botAdd,
    Save: SaveBots,
    ReSum: ReSumBots
  }
})();
